﻿using AutoMapper.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Volo.Abp.ObjectMapping;

namespace PHMEE.Admin
{
    /// <summary>
    /// 阈值设置模块服务类
    /// </summary>
    public class ThresholdAppService : PHMEEAdminAppService, IThresholdAppService
    {
        //private readonly IThresholdManager _thresholdManager;
        //private readonly IThresholdRepository _thresholdRepository;
        private IGuidGenerator _guidGenerator;
        private readonly IRepository<Threshold, Guid> _thresholdRepository;
        private readonly IRepository<Category, Guid> _categoryRepository;
        public ThresholdAppService(IRepository<Threshold, Guid> thresholdRepository, IRepository<Category, Guid> categoryRepository, IGuidGenerator guidGenerator)
        {
            _guidGenerator = guidGenerator;
            _thresholdRepository = thresholdRepository;
            _categoryRepository = categoryRepository;
        }
        /// <summary>
        /// 生成默认4个测点的GUID
        /// </summary>
        /// <returns></returns>
        public List<string> GetGuids()
        {
            List<string> guidList = new List<string>();
            for (int i = 0; i < 4; i++)
            {
                string guid = _guidGenerator.Create().ToString();
                //string guid = Guid.NewGuid().ToString();
                guidList.Add(guid);
            }
            return guidList;
        }
        /// <summary>
        /// 获取测点的id
        /// </summary>
        /// <returns></returns>
        public List<TestPointDto> GetPointIds()
        {
            return new List<TestPointDto>
            {
                new TestPointDto { Id = Guid.Parse("3a11f801-4e9d-3422-cfa9-a9069cc870ea"), Name = "电机驱动端" },
                new TestPointDto { Id = Guid.Parse("3a11f801-4e9d-43ae-4a2e-70db6540f894"), Name = "泵驱动端" },
                new TestPointDto { Id = Guid.Parse("3a11f801-4e9d-7353-9827-71058b22e13c"), Name = "鼓风机电机驱动端" },
                new TestPointDto { Id = Guid.Parse("3a11f801-4e9d-a4b0-d280-465a618272fc"), Name = "鼓风机泵驱动端" }
            };
        }
        /// <summary>
        /// 阈值分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ThresholdDto>> GetListAsync(PagedAndSortedResultRequestDto input)
        {
            var queryable = await _thresholdRepository.WithDetailsAsync(x => x.Category);

            queryable = queryable
                //.OrderBy(t => t.Name ?? "default")
                .Skip(input.SkipCount)
                .Take(input.MaxResultCount);

            var thresholds = await AsyncExecuter.ToListAsync(queryable);
            var count = await _thresholdRepository.GetCountAsync();

            // 使用 AutoMapper 转换数据
            var mappedThresholds = ObjectMapper.Map<List<Threshold>, List<ThresholdDto>>(thresholds);

            return new PagedResultDto<ThresholdDto>(count, mappedThresholds);
        }
        /// <summary>
        /// 查询所有的阈值
        /// </summary>
        /// <returns></returns>
        public async Task<List<ThresholdDto>> GetAllThresholdsAsync(Guid guid)
        {
            //var queryable = await _thresholdRepository.WithDetailsAsync(x => x.Category).Where(t => t.PointId == pointId);
            var queryable = _thresholdRepository.WithDetails(x => x.Category).Where(t => t.PointId == guid);

            // 不使用 Skip 和 Take，直接查询所有结果
            var thresholds = await AsyncExecuter.ToListAsync(queryable);

            // 使用 AutoMapper 转换数据
            var mappedThresholds = ObjectMapper.Map<List<Threshold>, List<ThresholdDto>>(thresholds);

            return mappedThresholds;
        }

        /// <summary>
        /// 查询所有启动的阈值
        /// </summary>
        /// <returns></returns>
        public async Task<List<ThresholdDto>> GetThresholdsIsTrueAsync(Guid guid)
        {
            //var queryable = await _thresholdRepository.WithDetailsAsync(x => x.Category).Where(t => t.PointId == pointId);
            var queryable = _thresholdRepository.WithDetails(x => x.Category).Where(t => t.PointId == guid && t.isEnable == true);

            // 不使用 Skip 和 Take，直接查询所有结果
            var thresholds = await AsyncExecuter.ToListAsync(queryable);

            // 使用 AutoMapper 转换数据
            var mappedThresholds = ObjectMapper.Map<List<Threshold>, List<ThresholdDto>>(thresholds);

            return mappedThresholds;
        }

        /// <summary>
        /// 查询采集定义的类型
        /// </summary>
        /// <returns></returns>
        public async Task<ListResultDto<CategoryLookupDto>> GetCategoriesAsync()
        {
            var queryable = await _categoryRepository.WithDetailsAsync();
            queryable = queryable.OrderBy(x => x.OrderBy);
            var categories = await AsyncExecuter.ToListAsync(queryable);
            var categoryLookupDtos = ObjectMapper.Map<List<Category>, List<CategoryLookupDto>>(categories);
            return new ListResultDto<CategoryLookupDto>(categoryLookupDtos);
        }
        /// <summary>
        /// 根据id查询采集定义类型
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<CategoryLookupDto> GetCategorieByIdAsync(Guid guid)
        {
            var category= await _categoryRepository.GetAsync(guid);
            return ObjectMapper.Map<Category, CategoryLookupDto>(category);
        }
        /// <summary>
        /// 创建阈值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateAsync(CreateThresholdDto input)
        {
            var threshold = ObjectMapper.Map<CreateThresholdDto, Threshold>(input);
            await _thresholdRepository.InsertAsync(threshold);
        }
        /// <summary>
        /// 创建阈值--支持多条
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        public async Task<int> CreateMultipleAsync(List<CreateThresholdDto> inputs)
        {
            int operationsCount = 0; // 记录操作的数量

            foreach (var input in inputs)
            {
                var existingThreshold = await _thresholdRepository.FirstOrDefaultAsync(t => t.PointId == input.PointId && t.CategoryId == input.CategoryId);

                if (existingThreshold != null)
                {
                    //如果存在，更新
                    existingThreshold.FirstThreshold = input.FirstThreshold;
                    existingThreshold.SecondThreshold = input.SecondThreshold;
                    existingThreshold.ThirdThreshold = input.ThirdThreshold;
                    existingThreshold.FourthThreshold = input.FourthThreshold;
                    existingThreshold.isEnable = input.IsEnable;
                    await _thresholdRepository.UpdateAsync(existingThreshold, autoSave: true);

                    operationsCount++;
                }
                else
                {
                    // 如果不存在，创建新实例并添加
                    var newThreshold = ObjectMapper.Map<CreateThresholdDto, Threshold>(input);
                    await _thresholdRepository.InsertAsync(newThreshold, autoSave: true);
                    operationsCount++;
                }
            }
            return operationsCount; // 返回操作的数量
        }
    }
}
